<script setup>
import * as echarts from "echarts";
import { ref, onMounted, onBeforeUnmount, watch } from "vue";

const emit = defineEmits(["loadComplete"]);

const props = defineProps({
  chartData: {
    type: Object,
    required: true
  }
});

const chartRef = ref(null);
let chartInstance = null;

// 图表基础配置
const baseOptions = {
  title: {
    text: "",
    left: "left"
  },
  tooltip: {
    trigger: "item"
  },
  grid: {
    containLabel: true,
    left: "5%", // 增加左边距
    right: "5%", // 增加右边距
    top: "10%",
    bottom: "12%" // 为底部图例预留空间
  },
  legend: {
    show: true,
    type: "scroll",
    orient: "horizontal",
    left: "center",
    right: "center", // 新增对称定位
    top: "bottom", // 置于图表底部
    padding: [10, 20], // 调整边距
    itemHeight: 14, // 固定图标高度
    textStyle: {
      width: 100, // 优化文本容器宽度
      overflow: "truncate",
      ellipsis: "...", // 明确省略符号
      fontSize: 12,
      color: "#666"
    },
    pageButtonItemGap: 5, // 翻页按钮间距
    pageButtonGap: 10, // 按钮与图例间距
    pageButtonPosition: "end", // 按钮位置
    pageIconColor: "#2c405a", // 翻页箭头颜色
    pageIconInactiveColor: "#aaa", // 禁用状态颜色
    pageTextStyle: {
      color: "#333" // 页码文字颜色
    },
    pageIconSize: 10, // 缩小翻页按钮
    itemGap: 8, // 缩小图例间距
    itemWidth: 20, // 缩小图标宽度
    formatter: name => (name.length > 6 ? name.slice(0, 5) + "..." : name)
  }
};

// 初始化/更新图表
const initChart = () => {
  if (chartInstance) chartInstance.dispose();

  // 合并基础配置与动态配置
  const mergedOptions = {
    ...props.chartData.options,
    ...baseOptions,
    series: props.chartData.options.series.map(series => ({
      ...series,
      type: props.chartData.chartType // 确保图表类型同步
    }))
  };

  chartInstance = echarts.init(chartRef.value);
  chartInstance.setOption(mergedOptions);
  emit("loadComplete");
};

// 响应窗口变化
const resizeHandler = () => {
  if (chartInstance) {
    chartInstance.resize({
      width: chartRef.value.offsetWidth,
      height: chartRef.value.offsetHeight
    });
  }
};

// 添加容器尺寸监听（需引入ResizeObserver）
const observer = new ResizeObserver(resizeHandler);
onMounted(() => {
  observer.observe(chartRef.value);
});
onBeforeUnmount(() => observer.disconnect());

onMounted(() => {
  window.addEventListener("resize", resizeHandler);
  initChart();
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeHandler);
  chartInstance?.dispose();
});
watch(
  () => props.chartData,
  () => nextTick(initChart),
  { deep: true }
);
</script>

<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart" />
  </div>
</template>

<style scoped lang="scss">
/* 样式可以根据需要调整 */
.chart-container {
  width: 100%;
  overflow-x: auto;
  margin-top: 16px;
  border: 1px solid rgba(203, 203, 205);
  background-color: rgba(247, 247, 252);
  border-radius: 4px;
  .chart {
    width: max-content; // 关键属性：根据内容自动扩展宽度
    min-width: calc(100vw - 54px);
    min-height: 350px;
  }
}
</style>
